<?php

namespace api\app\controller;

use api\app\model\UserModel;
use api\app\validate\UserValidate;
use api\swagger\response\SuccessResponse;
use cmf\controller\RestBaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Config;
use think\facade\Db;
use think\facade\Filesystem;

class UserController extends RestBaseController
{
    // 注册
    public function register(){
        // 接收数据
        $data = input('post.');

        // 查询账户是否已经注册
        $mobile = UserModel::where('mobile',$data['mobile'])->find();
        if($mobile){
            $this->error('手机号已被注册');
        }

        // 验证
        $validate = new UserValidate();
        $result = $validate->scene('register')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }

        // 验证验证码是否存在
        $check = checkSmsCode($data['mobile'], $data['code']);
        if(!$check){
            $this->error('验证码错误');
        }

        $randStr = createRandStr(8);
        $password = md5($data['password'].$randStr);
        $data['salt'] = $randStr;
        $data['password'] = $password;
        $data['create_time'] = time();
        $user = UserModel::create([
            'mobile' => $data['mobile'],
            'password' => $data['password'],
            'user_name' => $data['user_name'],
        ]);

        // 判断是否成功
        if($user){
            $this->success('注册成功');
        }else{
            $this->error('注册失败');
        }
    }
    // 登录
    public function login(){
        // 接收数据
        $data = input('post.');
        $validate = new UserValidate();
        $result = $validate->scene('login')->check($data);
        if(!$result){
            return error($validate->getError());
        }

        //查询账号
        $user = UserModel::where('mobile', $data['mobile'])->find();

        //验证验证码是否存在
        $check = checkSmsCode($data['mobile'], $data['code']);
        if(!$check){
            $this->error('验证码错误');
        }

        if(!$user){
            $this->error('该账号不存在');
        }
        // 生成 token
        $token = signToken($user->id, $user->mobile);
        return json(['status' => 'success', 'data' => ['token' => $token], 'message' => '登录成功']);
    }

    // 发送验证码
    public  function  sendCode()
    {
        $data = input('post.');
        sendSms($data['mobile']);
    }

    // 查询个人信息
    public function showUser()
    {
        $header = request()->header();
        if (!isset($header['token']) || empty($header['token'])) {
            $this->error('缺少token');
        }
        $key = new Key(config('app.jwt_key'), 'HS256');
        try {
            $res = JWT::decode($header['token'], $key);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $result = UserModel::field('id,user_name, image, mobile')
            ->where('id', $res->data->user_id)
            ->find();
        $result['image'] = request()->domain() . '/storage/' . $result['image'];
        $this->success('用户信息', $result);
    }

    // 修改个人信息
    public function editUser()
    {
        $token = request()->header();
        if(!isset($token['token']) || empty($token['token']))
        {
            $this->error('缺少token');
        }
        $key = new Key(config('app.jwt_key'), 'HS256');
        try {
            $res = JWT::decode($token['token'], $key);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }

        $data = input('post.');
        $user = UserModel::find($res->data->user_id);
        if (!$user) {
            return error('未查询到');
        }
        $image = request()->file('image');
        $result = Filesystem::disk('public')->putFile('image',$image);
        $image2 = request()->domain().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$result;
        $user->image = $image2;
        $user->mobile = $data['mobile'];
        $user->user_name = $data['user_name'];
        if ($user->save()) {
            return success('修改成功');
        } else {
            return error('修改失败');
        }
    }

    // 上传头像
    public function pushImage()
    {
        /*$mobile = input('mobile');
        $image = request()->file('image');
        $result = Filesystem::disk('public')->putFile('image',$image);

        if(!$mobile){
            return error('请输入手机号');
        }

        $image2 = request()->domain().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$result;
        $addImage = UserModel::where('mobile','=',$mobile)->find();
        if (!$addImage){
            $this->error('未查询到数据');
        }

        $addImage->image = $image2;

        if ($addImage->save()){
            return json(['code' => 1,
                'msg' => "上传成功" ,
                'data' => [
                    'url' => $image2,
                ]
            ]);
        }else{
            return json(['code' => 0,'msg' => "上传失败" , 'data' => null]);
        }*/

        // 使用token上传
        $image = request()->file('image');
        $image = Filesystem::disk('public')->putFile('image', $image);
        if ($image) {
            $this->success('图片地址',
                ['image' => request()->domain() . '/strong/' . $image]);

        }
    }
}
